﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Nova_DAL;
using System.Data.Common;
using System.Data.SqlClient;
using Nova_Common;
using Nova_MOD;
using Nova_Common.Extend;
using Nova_BLL;
using System.Collections.Generic;

public partial class Material_MaterialList : System.Web.UI.Page
{
    Nova_DAL.DbHelper_ERP dbHelper_ERP = new DbHelper_ERP();
    Nova_DAL.DbHelper access = new DbHelper();
    DbCommand cmd = null;
    string strSQL = "";

    Nova_BLL.MaterialType Nova_BLL_MaterialType = new Nova_BLL.MaterialType();
    TMaterialGroupInfoBll MaterialGroupBll = new TMaterialGroupInfoBll();
    string strMessage = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (this.hidden.Value != "" && this.hidden.Value != "undefined")//判断是否是模态关闭后刷新页面
        {
            bind();
            hidden.Value = "";
        }

        if (!IsPostBack)
        {
            Bind_ddlGroupType();
            bind();
        }
    }

    /// <summary>
    /// 绑定物料归属
    /// </summary>
    private void Bind_ddlGroupType()
    {
        try
        {
            List<TMaterialGroupInfo> list = MaterialGroupBll.GetList();
            DataTable dt = TableList.ToDataTable(list);
            ddlGroupType.DataSource = dt;
            ddlGroupType.DataBind();
            ddlGroupType.Items.Insert(0, new ListItem("====请选择====", "-1"));
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }

    /// <summary>
    /// 清空ddl绑定信息
    /// </summary>
    /// <param name="ddl"></param>
    protected void ClearDropDown(DropDownList ddl)
    {
        ddl.Items.Clear();
        ddl.Items.Insert(0, new ListItem("====全部====", "-1"));
    }

    /// <summary>
    /// 绑定GV
    /// </summary>
    protected void bind()
    {
        strSQL = @"Select TBM.PID,TBM.S01,TBM.Mat_Name,TBM.Mat_Code,TBM.Unit_Base,TBM.S03,TBM.S04,TBM.TM01,TBM.S02,TBM.S05,TBM.S06,TBM.OID,
                TBM.GroupType,TBM.MiniNum,TMG.MaterialGroupName,TBM.TM03,TBM.CDT FROM dbo.TBase_Material AS TBM 
                LEFT JOIN dbo.TMaterialGroupInfo AS TMG ON TBM.GroupType = TMG.MaterialGroupType WHERE 1=1 ";
        if (txtMat_Name.Text != "")
        {
            strSQL += " and Mat_Name like '%" + txtMat_Name.Text.ToString().Trim() + "%'";
        }

        if (txtMat_Code.Text != "")
        {
            strSQL += " and Mat_Code like '%" + txtMat_Code.Text.ToString().Trim() + "%'";
        }
        if(ddlGroupType.SelectedIndex !=0)
        {
            strSQL += " and TBM.GroupType = " + ddlGroupType.SelectedValue + "";
        }
        if(!string.IsNullOrEmpty(txt_S01.Text))
        {
            strSQL += " and TBM.S01 like '%" + txt_S01.Text.ToString().Trim() + "%'";
        }

        strSQL += " ORDER BY CDT DESC ";

        cmd = access.GetSqlStringCommond(strSQL);
        gv.DataSource = access.ExecuteDataSet(cmd);
        gv.DataBind();

    }


    protected void ibtnSearch_Click(object sender, ImageClickEventArgs e)
    {
        bind();
    }

    protected void ibtnDel_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            LinkButton lbtn_Mat_Code = null;
            for (int i = 0; i < gv.Rows.Count; i++)
            {
                CheckBox chkSelect = (CheckBox)gv.Rows[i].FindControl("chkSelect");
                Label lbOID = (Label)gv.Rows[i].FindControl("lbOID");
                if (chkSelect.Checked)
                {
                    //if (lbOID.Text == "MES")
                    //{
                    //    ShowBox.MessageBox(this.Page, "MES系统同步的物料不能删除!");
                    //    continue;
                    //}
                    lbtn_Mat_Code = (LinkButton)gv.Rows[i].FindControl("lbtn_Mat_Code");
                    strSQL = @" delete from TBase_Interface where MAT_CODE='" + lbtn_Mat_Code.Text.Trim() + "'";
                    strSQL += "DELETE FROM TBase_Material WHERE PID = '" + gv.DataKeys[gv.Rows[i].RowIndex].Value.ToString() + "'";
                    cmd = access.GetSqlStringCommond(strSQL);
                    access.ExecuteNonQuery(cmd);
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
        bind();
    }

    protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton lbtn_Mat_Code = (LinkButton)e.Row.FindControl("lbtn_Mat_Code");

            //string str = string.Format("javascript:document.getElementById('{1}').value=window.open('MaterialUpdate.aspx?Ram=" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + "&Mode={0}&PID={2}', window, 'Height=220px,Width=600px,top=250, left=500, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no');document.URL=location.href;void(0);",
            // "Update", hidden.ClientID, gv.DataKeys[e.Row.RowIndex].Value.ToString());
            //lbtn_Mat_Code.Attributes.Add("onclick", str);

            CheckBox chkSelect = (CheckBox)e.Row.FindControl("chkSelect");

            //有库存的物料不允许选取
            strSQL = @"SELECT COUNT(1)
                        FROM TBase_Storage TBS 
                        LEFT JOIN dbo.TBase_Interface as TBI ON TBS.SEC_MAT_ID = TBI.SEC_MAT_ID
                        WHERE TBI.MAT_CODE='" + lbtn_Mat_Code.Text + "'";
            cmd = access.GetSqlStringCommond(strSQL);
            if (Convert.ToInt32(access.ExecuteScalar(cmd)) > 0)
            {
                chkSelect.Enabled = false;
            }

        }
    }

    protected void pager_PageChanged(object sender, EventArgs e)
    {
        bind();
    }

    protected void ibtn_DR_Click(object sender, ImageClickEventArgs e)
    {
        //int iFlag = ExcelToSql.ImportSql(File1, "TP_Budget", txt_Title.Text.Trim());
        //if (iFlag == 1)
        //{
        //    bind();//成功
        //}
        //else if (iFlag == 2)
        //{
        //    ShowBox.ShowBox.MessageBox(this, "表名不存在");
        //}
        //else if (iFlag == 3)
        //{
        //    ShowBox.ShowBox.MessageBox(this, "excel里的字段和数据库表里的字段不匹配");
        //}
        //else if (iFlag == 4)
        //{
        //    ShowBox.ShowBox.MessageBox(this, "转换数据类型时发生错误");
        //}
        //else if (iFlag == 5)
        //{
        //    ShowBox.ShowBox.MessageBox(this, "Excel格式不能读取");
        //}
        //else if (iFlag == 6)
        //{
        //    ShowBox.ShowBox.MessageBox(this, "Excel文件不存在");
        //}
    }

    protected void ibtn_ERP_Click(object sender, ImageClickEventArgs e)
    {
        string strErr = "";
        string strText = "";
        int iflag = 0;

        strSQL = @"SELECT ID FROM TB_OrgCode";
        cmd = access.GetSqlStringCommond(strSQL);
        DataSet ds_OrgCode = access.ExecuteDataSet(cmd);
        string str = ds_OrgCode.Tables[0].Rows[0][0].ToString();

        strSQL = @"SELECT ZBJLH,XFSJ,ItemCod,LPMC,LPGG,DW,DWMC,FL,FLMC,CZLX,ZT,FKSJ,BZ FROM dbo.ERP_WMS_WLBM WHERE OrgCode='" + str + "' AND ZT=0";
        cmd = dbHelper_ERP.GetSqlStringCommond(strSQL);
        DataSet ds = dbHelper_ERP.ExecuteDataSet(cmd);
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                string strPID = "";
                string strczlx = ds.Tables[0].Rows[i]["czlx"].ToString().ToUpper();

                strSQL = "SELECT PID FROM TBase_Material WHERE Mat_Code='" + ds.Tables[0].Rows[i]["ItemCod"].ToString().Trim() + "'";
                cmd = access.GetSqlStringCommond(strSQL);
                DataSet ds_TBM = access.ExecuteDataSet(cmd);

                if (ds_TBM != null && ds_TBM.Tables[0].Rows.Count > 0)
                {
                    strPID = ds_TBM.Tables[0].Rows[0][0].ToString();
                    if (strczlx == "I")
                    {
                        iflag = 2;
                        strErr = "物料编码为：" + ds.Tables[0].Rows[i]["ItemCod"].ToString().Trim() + "的物料已经存在，请将操作类型修改为U修改。";
                    }
                }
                if (iflag != 2)
                {
                    try
                    {
                        if (strczlx == "I")
                        {
                            strSQL = @"INSERT INTO TBase_Material(Mat_Name,Mat_Code,Unit_Base,S01,S04,S06,S07) 
                                        values(@Mat_Name,@Mat_Code,@Unit_Base,@S01,@S04,@S06,@S07)";
                        }
                        else if (strczlx == "U")
                        {
                            int icount_M = iMaterial(ds.Tables[0].Rows[i]["ItemCod"].ToString().Trim());
                            if (icount_M == 0)
                            {
                                iflag = 2;
                                strErr = "编码为： " + ds.Tables[0].Rows[i]["ItemCod"].ToString().Trim() + "的物料不在仓库中，请更改操作类型为 I 后，再次导入！";
                            }
                            else
                            {
                                strSQL = @"UPDATE TBase_Material SET Mat_Name=@Mat_Name,Mat_Code=@Mat_Code,Unit_Base=@Unit_Base,S01=@S01
                                                        ,S04=@S04,S06=@S06,S07=@S07 WHERE PID='" + strPID + "'";
                            }
                        }
                        else
                        {
                            strSQL = @"SELECT COUNT(1)
                                            FROM TBase_Storage TBS 
                                            LEFT JOIN dbo.TBase_Interface as TBI ON TBS.SEC_MAT_ID = TBI.SEC_MAT_ID
                                            WHERE TBI.MAT_CODE='" + ds.Tables[0].Rows[i]["ItemCod"].ToString().Trim() + "'";
                            cmd = access.GetSqlStringCommond(strSQL);
                            if (Convert.ToInt32(access.ExecuteScalar(cmd)) != 0)
                            {
                                iflag = 2;
                                strErr = "物料编码为：" + ds.Tables[0].Rows[i]["ItemCod"].ToString().Trim() + "的物料已经入库，WMS不允许删除！";
                            }
                            else
                            {
                                strSQL = "DELETE TBase_Material WHERE PID='" + strPID + "'";
                            }
                        }
                        if (iflag != 2)
                        {
                            cmd = access.GetSqlStringCommond(strSQL);
                            access.AddInParameter(cmd, "@Mat_Name", DbType.String, ds.Tables[0].Rows[i]["LPMC"].ToString().Trim());
                            access.AddInParameter(cmd, "@Mat_Code", DbType.String, ds.Tables[0].Rows[i]["ItemCod"].ToString().Trim());
                            access.AddInParameter(cmd, "@Unit_Base", DbType.String, ds.Tables[0].Rows[i]["DWMC"].ToString().Trim());
                            access.AddInParameter(cmd, "@S01", DbType.String, ds.Tables[0].Rows[i]["LPGG"].ToString().Trim());
                            access.AddInParameter(cmd, "@S04", DbType.String, ds.Tables[0].Rows[i]["FLMC"].ToString().Trim());
                            access.AddInParameter(cmd, "@S06", DbType.String, ds.Tables[0].Rows[i]["DW"].ToString().Trim());
                            access.AddInParameter(cmd, "@S07", DbType.String, ds.Tables[0].Rows[i]["FL"].ToString().Trim());
                            iflag = access.ExecuteNonQuery(cmd);
                            if (iflag >= 0)
                            {
                                iflag = 1;
                                strErr = "";
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        iflag = 2;
                        strErr = ex.Message.ToString();
                    }
                }
                strText += strErr;
                strSQL = "UPDATE ERP_WMS_WLBM SET zt='" + iflag + "',fksj='" + DateTime.Now.ToString() + "',bz='" + strErr + "' WHERE zbjlh='" + ds.Tables[0].Rows[i]["zbjlh"].ToString() + "'";
                cmd = dbHelper_ERP.GetSqlStringCommond(strSQL);
                dbHelper_ERP.ExecuteNonQuery(cmd);
                iflag = 0;
                strErr = "";
            }

        }

        if (strText == "")
        {
            ShowBox.MessageBox(this.Page, "导入成功！");
        }
        else
        {
            ShowBox.MessageBox(this.Page, "导入存在错误，信息已反写！");
        }
    }

    protected int iMaterial(string strMAT_CODE)
    {
        int iMaterial = 0;
        strSQL = "SELECT * FROM TBase_Material WHERE MAT_CODE='" + strMAT_CODE + "'";
        cmd = access.GetSqlStringCommond(strSQL);
        DataSet ds_M = access.ExecuteDataSet(cmd);
        if (ds_M != null && ds_M.Tables[0].Rows.Count > 0)
        {
            iMaterial = 1;
        }
        return iMaterial;
    }

    protected void gv_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gv.PageIndex = e.NewPageIndex;
        bind();  //重新绑定GridView

    }


    /// <summary>
    /// 合并GridView中某列相同信息的行（单元格） 
    /// </summary>
    /// <param name="GridView1">GridView</param>
    /// <param name="cellNum">第几列</param>
    public static void GroupRows(GridView GridView1, int cellNum)
    {
        int i = 0, rowSpanNum = 1;
        while (i < GridView1.Rows.Count - 1)
        {
            GridViewRow gvr = GridView1.Rows[i];

            for (++i; i < GridView1.Rows.Count; i++)
            {
                GridViewRow gvrNext = GridView1.Rows[i];
                if (gvr.Cells[cellNum].Text == gvrNext.Cells[cellNum].Text)
                {
                    gvrNext.Cells[cellNum].Visible = false;
                    rowSpanNum++;
                }
                else
                {
                    gvr.Cells[cellNum].RowSpan = rowSpanNum;
                    rowSpanNum = 1;
                    break;
                }

                if (i == GridView1.Rows.Count - 1)
                {
                    gvr.Cells[cellNum].RowSpan = rowSpanNum;
                }
            }
        }
    }


}
